package cn.sccl.common.security;

import cn.sccl.common.exception.NotNullException;
import cn.sccl.dirms.security.model.Authority;
import cn.sccl.dirms.security.model.User;
import cn.sccl.dirms.security.model.UserPrincipalDetails;
import cn.sccl.dirms.security.service.AuthorityManager;
import cn.sccl.dirms.security.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * Spring-Security 用户数据构造类。
 * =====================================================================================================================
 * 用于从用户表根据关键字（如用户名，用户唯一标识，视表结构设计而定）构造用户细节（涵盖密码，菜单，权限等，视业务设计而定）
 * 。在用户登录等验证权限的行为发生时，与同样由ProviderManager派生的AuthenticationProvider(验证异常由此类抛出)生成的
 * Authentication进行比对完成鉴权行为。
 * =====================================================================================================================
 * 其调用顺序为
 * AbstractAuthenticationProcessingFilter->UsernamePasswordAuthenticationFilter->
 * ProviderManager->AbstractUserDetailsAuthenticationProvider->DaoAuthenticationProvider->本类
 * =====================================================================================================================
 * Created by 杨浩宇 on 2016/2/24 0024.
 *
 * @version 1.0
 */
@Service(value = "userDetailsService")
public class UserDetailsServiceImpl  implements UserDetailsService {

    @Autowired
    private UserManager userManager;

    @Autowired
    private AuthorityManager authorityManager;


    public UserPrincipalDetails loadUserByUsername(String username) throws Exception {
        if (username != null && !username.isEmpty()) {
            User user = userManager.findByName(username);//根据用户名查询用户
            List<Authority> authorityList = new ArrayList<Authority>();
            if (user == null) {
                throw new Exception(username + " 不存在");
            } else {

                authorityList = authorityManager.findByUserId(user.getId());
            }
            return new UserPrincipalDetails(user.getId(), user.getName(), user.getUserName(), user.getPassword(),
                    authorityList);
        } else {
            throw new NotNullException("用户名");
        }
    }
}
